package com.snail.auth.action;

import com.alibaba.fastjson.JSON;
import com.common.ResultUtil;
import com.common.entity.BaseController;
import com.common.util.StringUtil;
import com.common.util.http.HttpUtil;
import com.snail.auth.entity.AuthOrg;
import com.snail.auth.service.AuthOrgService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 组织机构Controller
 */
@RestController
@RequestMapping("auth/org")
public class AuthOrgController extends BaseController {
    @Autowired
    private AuthOrgService orgService;
    @GetMapping
    public Map list() {
        Map<String, Object> params = new HashMap<>();
        if (request.getParameter("functionType") != null) {
            params.put("functionType", request.getParameter("functionType"));
        }
        List<AuthOrg> orgs = orgService.list(params);
        return ResultUtil.result(orgs);
    }

    @GetMapping(value = "/{id}")
    public Map<String, Object> input(@PathVariable Long id) {
        AuthOrg org = orgService.getByKey(id);
        Map<String, Object> result = JSON.parseObject(JSON.toJSONString(org));
        AuthOrg parentOrg = orgService.getByKey(org.getParentId());
        if (parentOrg != null) {
            result.put("parentName", parentOrg.getName());
        }
        return ResultUtil.result(result);
    }

    @PostMapping
    public Map<String, Object> save(AuthOrg org) {
        boolean isAdd = false;
        if(org.getId()==null || !orgService.exist(org.getId())){
            isAdd = true;
        }
        if (StringUtil.isEmpty(org.getId())) {
            org.setId(orgService.newId(org.getParentId(), org.getFunctionType()));
        }
        org.setFlag(0);
        orgService.save(org);
        Map<String,Object> params = new HashMap<>();
        params.put("id", org.getId().toString());
        params.put("name", org.getId()+"-"+org.getName());
        params.put("type", "assignment");
        return ResultUtil.result(org);
    }

    @DeleteMapping(value = "/{id}")
    public Map<String, Object> del(@PathVariable Long id) {
        orgService.del(id);
        return ResultUtil.result();
    }

    @ApiOperation(value = "部门结构树")
    @GetMapping("/tree")
    public Map<String, Object> tree() {
        return ResultUtil.result(orgService.treeData());
    }

}
